package com.showcai.core.filter;

import org.apache.poi.ss.formula.functions.T;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Baggio on 2018-9-3.
 */
public class MyHttpServletRequestWrapper extends HttpServletRequestWrapper {
    private String url;
    private Map<String, String[]> params = new HashMap<String, String[]>();

    public MyHttpServletRequestWrapper(HttpServletRequest request, String url) {
        super(request);
        this.url = url;
        this.params.putAll(request.getParameterMap());
    }

    //重载一个构造方法
    public MyHttpServletRequestWrapper(HttpServletRequest request, Map<String, Object> extendParams) {
        super(request);
        addAllParameters(extendParams);//这里将扩展参数写入参数表
    }

    @Override
    public Enumeration<T> getParameterNames() {
        return this.getRequest().getParameterNames();
    }

    @Override
    public String getServletPath() {
        //spring mvc 根据这个方法获得路径
        return url;
      /*  if(super.getDispatcherType().name().equals("REQUEST"))//当是客服端请求服务器类型时，设置新url
//新url地址为spring  mvc controller前的地址
            return url;
        else//当不是请求类型时，此时为服务器跳转，转发为FORWARD等等，默认服务器跳转地址
//服务器跳转的地址为/page/bjcl/order/user.jsp，是controller return后的地址。
            return super.getServletPath();*/
    }

    @Override
    public String getRequestURI() {
        return url;
    }

    @Override
    public String getParameter(String name) {//重写getParameter，代表参数从当前类中的map获取
        String[] values = params.get(name);
        if (values == null || values.length == 0) {
            return null;
        }
        return values[0];
    }

    @Override
    public Map getParameterMap() {
        return params;
    }

    public String[] getParameterValues(String name) {//同上
        return params.get(name);
    }


    public void addAllParameters(Map<String, Object> otherParams) {//增加多个参数
        for (Map.Entry<String, Object> entry : otherParams.entrySet()) {
            addParameter(entry.getKey(), entry.getValue());
        }
    }

    public void addParameter(String name, Object value) {//增加参数
        System.out.println("addParameter");
        System.out.println("name==>" + name);
        System.out.println("value==>" + value);
        if (value != null) {
            if (value instanceof String[]) {
                params.put(name, (String[]) value);
            } else if (value instanceof String) {
                params.put(name, new String[]{(String) value});
            } else {
                params.put(name, new String[]{String.valueOf(value)});
            }
        }
    }
}

